package com.bfsuol.yihang.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bfsuol.DocumentTypeConstants;
import com.bfsuol.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.utils.StringUtils;
import com.bfsuol.bfsuolframework.security.annotations.*;
import com.bfsuol.yihang.cars.api.QueryVehicleService;
import com.bfsuol.yihang.cars.dto.VehicleDTO;
import com.bfsuol.yihang.documentFiles.api.CommandDocumentFilesService;
import com.bfsuol.yihang.documentFiles.api.QueryDocumentFilesService;
import com.bfsuol.yihang.documentFiles.dto.DocumentFilesDTO;
import com.bfsuol.yihang.documentFiles.entity.DocumentFilesEntity;
import com.bfsuol.yihang.documents.api.CommandDocumentService;
import com.bfsuol.yihang.documents.api.QueryDocumentService;
import com.bfsuol.yihang.documents.dto.DocumentDTO;
import com.bfsuol.yihang.file.entity.FileManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/yihang/documentFiles")
public class DocumentFilesController extends SpringControllerSupport {


    @Autowired
    private QueryDocumentFilesService queryDocumentFilesService;
    @Autowired
    private CommandDocumentFilesService commandDocumentFilesService;
    @Autowired
    private QueryDocumentService queryDocumentService;

    @SecPrivilege(title = "文档详情管理")
    @RequestMapping("/index/{id}")
    public ModelAndView index(@PathVariable("id") Long id,Model model){
        ModelAndView modelAndView = new ModelAndView();
        model.addAttribute("documentId",id);
        model.addAttribute("document",queryDocumentService.getById(id));
        modelAndView.setViewName(getViewNamedPath("index"));
        return modelAndView;
    }

    @SecList
    @RequestMapping("/list")
    public ModelAndView list(
            DocumentFilesDTO documentDTO,
            @ModelAttribute("page") Pagination page){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = new Page(page.getDefaultCurrentPage(),page.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DocumentFilesDTO> documentFilesDTOPage = queryDocumentFilesService.page(page1,documentDTO);
        documentFilesDTOPage.getRecords().stream().forEach(item->{
            if(!StringUtils.isBlank(item.getDocumentType())){
                item.setDocumentType(DocumentTypeConstants.map.get(item.getDocumentType()));
            }
        });

        // 方法二：Java8中使用lambda表达式
        Collections.sort(documentFilesDTOPage.getRecords(),
                Comparator.comparing(DocumentFilesDTO::getDocumentType));

        page.setItems(documentFilesDTOPage.getRecords());
        page.setTotalRecord((int) documentFilesDTOPage.getTotal());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("list"));
        return modelAndView;
    }


    @SecDelete
    @RequestMapping("/delete/{id}")
    public @ResponseBody
    MessageJson delete(@PathVariable("id") Long id) {
        if(id != null){
            commandDocumentFilesService.deleteById(id);
        }
        return MessageJson.information("删除成功");
    }

    @RequestMapping({"/download/{id}"})
    public void download(@PathVariable("id") Long id,
                         HttpServletRequest request,
                         HttpServletResponse response, @RequestParam(value = "realname",required = false) Boolean realname) {
        try {
            DocumentFilesDTO documentFilesDTO = (DocumentFilesDTO)queryDocumentFilesService.getById(id);
            String fileName = documentFilesDTO.getFileName();

            String userAgent = request.getHeader("User-Agent");
            boolean isIE = false;
            if(userAgent.indexOf("MSIE") > 0) {
                isIE = true;
            }

            if(isIE) {
                fileName = new String(fileName.getBytes("gb2312"), "iso-8859-1");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }

            byte[] buffer = documentFilesDTO.getFile();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException var14) {
            var14.printStackTrace();
        }

    }
}
